package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.SocialPositions;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.SocialPositionsRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class SocialPositionsService {

    private final SocialPositionsRepository socialPositionsRepository;
    private final ApplicationRepository applicationRepository;

    public SocialPositionsService(SocialPositionsRepository socialPositionsRepository, ApplicationRepository applicationRepository) {
        this.socialPositionsRepository = socialPositionsRepository;
        this.applicationRepository = applicationRepository;
    }

    public SocialPositions createSocialPositions(Long applicationId, SocialPositions socialPositions) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        socialPositions.setApplication(application);
        socialPositions.setCreatedAt(LocalDateTime.now());
        socialPositions.setUpdatedAt(LocalDateTime.now());
        return socialPositionsRepository.save(socialPositions);
    }

    public List<SocialPositions> getSocialPositionsByApplicationId(Long applicationId) {
        return socialPositionsRepository.findByApplicationId(applicationId);
    }

    public Optional<SocialPositions> getSocialPositionsById(Long id) {
        return socialPositionsRepository.findById(id);
    }

    public SocialPositions updateSocialPositions(Long id, SocialPositions updatedSocialPositions) {
        SocialPositions existingSocialPositions = socialPositionsRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("SocialPositions not found"));

        existingSocialPositions.setStartDate(updatedSocialPositions.getStartDate());
        existingSocialPositions.setEndDate(updatedSocialPositions.getEndDate());
        existingSocialPositions.setOrganizationName(updatedSocialPositions.getOrganizationName());
        existingSocialPositions.setPosition(updatedSocialPositions.getPosition());
        existingSocialPositions.setRemarks(updatedSocialPositions.getRemarks());
        existingSocialPositions.setUpdatedAt(LocalDateTime.now());

        return socialPositionsRepository.save(existingSocialPositions);
    }

    public void deleteSocialPositions(Long id) {
        socialPositionsRepository.deleteById(id);
    }
}

